<template>
    <div v-if="show" class="numcard numcardItem1">
        <span class="real-time-num" ref="numbers" :style="{ color: color }">{{ formattedNumber }}</span>
    </div>
</template>
  
<script setup lang="ts">
import { ref, watch, computed, onMounted, defineProps } from 'vue'
import { gsap } from 'gsap';
const show = ref(true)
const numbers = ref(null)
const showComma = ref(false) // 是否显示千分位逗号
const rawNumber = ref(0)
const props = defineProps({
    number: {
        type: Number,
        default() {
            return 0;
        },
    },
    comma: { // 通过props控制是否显示千分位
        type: Boolean,
        default: false
    },
    delay: {
        type: [Number, String],
        default() {
            return 0;
        },
    },
    color: {
        type: String,
        default: false
    },
})
watch(() => props.number, (newVal) => {
    console.log(newVal)
    if (show.value) {
        nextTick(() => {
            currentNumber.value = 0
            animateNumber(currentNumber.value, newVal);
        });
    }
})
watch(show, (newVal) => {
    console.log(newVal)
    nextTick(() => {
        currentNumber.value = 0
        animateNumber(currentNumber.value, number.value);
    });
})

const formattedNumber = computed(() => {
    if (showComma.value) {
        return rawNumber.value.toLocaleString(); // 格式化数字为千分位格式
    }
    return rawNumber.value;
})
const currentNumber = computed({
    get: function () {
        return rawNumber.value;
    },
    set(value) {
        rawNumber.value = value;
    }
})
const animateNumber = (start, end) => {
    gsap.to(numbers.value, {
        currentNumber: end,
        duration: 2,
        // delay: parseFloat(numbers.value.dataset.index * 0.5),  // 添加这一行
        roundProps: 'currentNumber',
        ease: 'power1.out',
        onUpdate: () => {
            currentNumber.value = Math.round(currentNumber.value);
        },
    });
}
onMounted(() => {
    showComma.value = props.comma;
    if (show.value) {
        currentNumber.value = 0
        animateNumber(currentNumber.value, props.number);
    }
})
</script>
  
<style lang="scss">
.numcardItem1 {
    .real-time-num {
        width: auto !important;
        font-size: 22px;
        font-weight: bold;
        font-style: normal;
        color: #11FFFE;
        animation: slideUp 1s forwards;
    }
}

@keyframes slideUp {
    from {
        transform: translateY(100%);
        opacity: 0;
    }

    to {
        transform: translateY(0);
        opacity: 1;
    }
}
</style>
  